package com.zenithmind.document.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zenithmind.common.context.UserContext;
import com.zenithmind.common.result.Result;
import com.zenithmind.document.pojo.dto.DocumentCreateDTO;
import com.zenithmind.document.pojo.dto.DocumentUpdateDTO;
import com.zenithmind.document.pojo.dto.DocumentUploadDTO;
import com.zenithmind.document.pojo.query.DocumentQueryDTO;
import com.zenithmind.document.pojo.vo.DocumentDetailVO;
import com.zenithmind.document.pojo.vo.DocumentStatisticsVO;
import com.zenithmind.document.pojo.vo.DocumentVO;
import com.zenithmind.document.service.DocumentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 文档管理控制器
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Tag(name = "文档管理", description = "文档管理相关接口")
@RestController
@RequestMapping("/api/v1/documents")
@RequiredArgsConstructor
public class DocumentController {

    private final DocumentService documentService;

    @Operation(summary = "上传文档", description = "上传文档文件")
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result<DocumentVO> uploadDocument(@Valid DocumentUploadDTO uploadDTO) {
        DocumentVO document = documentService.uploadDocument(uploadDTO);
        return Result.success(document);
    }

    @Operation(summary = "创建文档", description = "创建新文档")
    @PostMapping
    public Result<DocumentVO> createDocument(@Valid @RequestBody DocumentCreateDTO createDTO) {
        DocumentVO document = documentService.createDocument(createDTO);
        return Result.success(document);
    }

    @Operation(summary = "更新文档", description = "更新文档信息")
    @PutMapping("/{id}")
    public Result<Boolean> updateDocument(
            @Parameter(description = "文档ID") @PathVariable String id,
            @Valid @RequestBody DocumentUpdateDTO updateDTO) {
        Boolean result = documentService.updateDocument(id, updateDTO);
        return Result.success(result);
    }

    @Operation(summary = "删除文档", description = "删除指定文档")
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteDocument(@Parameter(description = "文档ID") @PathVariable String id) {
        Boolean result = documentService.deleteDocument(id);
        return Result.success(result);
    }

    @Operation(summary = "批量删除文档", description = "批量删除文档")
    @DeleteMapping("/batch")
    public Result<Boolean> batchDeleteDocuments(@RequestBody List<String> ids) {
        Boolean result = documentService.batchDeleteDocuments(ids);
        return Result.success(result);
    }

    @Operation(summary = "恢复文档", description = "恢复已删除的文档")
    @PostMapping("/{id}/restore")
    public Result<Boolean> restoreDocument(@Parameter(description = "文档ID") @PathVariable String id) {
        Boolean result = documentService.restoreDocument(id);
        return Result.success(result);
    }

    @Operation(summary = "分页查询文档", description = "分页查询文档列表")
    @PostMapping("/page")
    public Result<IPage<DocumentVO>> getDocumentPage(@Valid @RequestBody DocumentQueryDTO queryDTO) {
        IPage<DocumentVO> page = documentService.getDocumentPage(queryDTO);
        return Result.success(page);
    }

    @Operation(summary = "获取文档详情", description = "获取文档详细信息")
    @GetMapping("/{id}")
    public Result<DocumentDetailVO> getDocumentDetail(@Parameter(description = "文档ID") @PathVariable String id) {
        String userId = UserContext.getUserId();
        DocumentDetailVO document = documentService.getDocumentDetail(id, userId);
        return Result.success(document);
    }

    @Operation(summary = "搜索文档", description = "根据关键词搜索文档")
    @GetMapping("/search")
    public Result<List<DocumentVO>> searchDocuments(
            @Parameter(description = "关键词") @RequestParam String keyword,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "20") Integer limit) {
        String userId = UserContext.getUserId();
        List<DocumentVO> documents = documentService.searchDocuments(keyword, userId, limit);
        return Result.success(documents);
    }

    @Operation(summary = "全文搜索文档", description = "全文搜索文档内容")
    @GetMapping("/fulltext-search")
    public Result<List<DocumentVO>> fullTextSearchDocuments(
            @Parameter(description = "搜索文本") @RequestParam String searchText,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "20") Integer limit) {
        String userId = UserContext.getUserId();
        List<DocumentVO> documents = documentService.fullTextSearchDocuments(searchText, userId, limit);
        return Result.success(documents);
    }

    @Operation(summary = "获取用户文档", description = "获取用户创建的文档")
    @GetMapping("/my")
    public Result<List<DocumentVO>> getUserDocuments(
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "20") Integer limit) {
        String userId = UserContext.getUserId();
        List<DocumentVO> documents = documentService.getUserDocuments(userId, limit);
        return Result.success(documents);
    }

    @Operation(summary = "获取分类文档", description = "获取指定分类的文档")
    @GetMapping("/category/{categoryId}")
    public Result<List<DocumentVO>> getCategoryDocuments(
            @Parameter(description = "分类ID") @PathVariable String categoryId,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "20") Integer limit) {
        String userId = UserContext.getUserId();
        List<DocumentVO> documents = documentService.getCategoryDocuments(categoryId, userId, limit);
        return Result.success(documents);
    }

    @Operation(summary = "获取热门文档", description = "获取热门文档列表")
    @GetMapping("/hot")
    public Result<List<DocumentVO>> getHotDocuments(
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        String userId = UserContext.getUserId();
        List<DocumentVO> documents = documentService.getHotDocuments(userId, limit);
        return Result.success(documents);
    }

    @Operation(summary = "获取最新文档", description = "获取最新文档列表")
    @GetMapping("/latest")
    public Result<List<DocumentVO>> getLatestDocuments(
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        String userId = UserContext.getUserId();
        List<DocumentVO> documents = documentService.getLatestDocuments(userId, limit);
        return Result.success(documents);
    }

    @Operation(summary = "获取推荐文档", description = "获取推荐文档列表")
    @GetMapping("/recommended")
    public Result<List<DocumentVO>> getRecommendedDocuments(
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        String userId = UserContext.getUserId();
        List<DocumentVO> documents = documentService.getRecommendedDocuments(userId, limit);
        return Result.success(documents);
    }

    @Operation(summary = "获取相关文档", description = "获取相关文档列表")
    @GetMapping("/{id}/related")
    public Result<List<DocumentVO>> getRelatedDocuments(
            @Parameter(description = "文档ID") @PathVariable String id,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        String userId = UserContext.getUserId();
        List<DocumentVO> documents = documentService.getRelatedDocuments(id, userId, limit);
        return Result.success(documents);
    }

    @Operation(summary = "获取收藏文档", description = "获取用户收藏的文档")
    @GetMapping("/favorites")
    public Result<List<DocumentVO>> getFavoriteDocuments(
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "20") Integer limit) {
        String userId = UserContext.getUserId();
        List<DocumentVO> documents = documentService.getFavoriteDocuments(userId, limit);
        return Result.success(documents);
    }

    @Operation(summary = "获取最近访问文档", description = "获取最近访问的文档")
    @GetMapping("/recent")
    public Result<List<DocumentVO>> getRecentDocuments(
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        String userId = UserContext.getUserId();
        List<DocumentVO> documents = documentService.getRecentDocuments(userId, limit);
        return Result.success(documents);
    }

    @Operation(summary = "下载文档", description = "下载文档文件")
    @GetMapping("/{id}/download")
    public Result<byte[]> downloadDocument(@Parameter(description = "文档ID") @PathVariable String id) {
        String userId = UserContext.getUserId();
        byte[] fileData = documentService.downloadDocument(id, userId);
        return Result.success(fileData);
    }

    @Operation(summary = "预览文档", description = "预览文档")
    @GetMapping("/{id}/preview")
    public Result<String> previewDocument(@Parameter(description = "文档ID") @PathVariable String id) {
        String userId = UserContext.getUserId();
        String previewUrl = documentService.previewDocument(id, userId);
        return Result.success(previewUrl);
    }

    @Operation(summary = "转换文档格式", description = "转换文档为指定格式")
    @PostMapping("/{id}/convert")
    public Result<String> convertDocument(
            @Parameter(description = "文档ID") @PathVariable String id,
            @Parameter(description = "目标格式") @RequestParam String targetFormat) {
        String userId = UserContext.getUserId();
        String newDocumentId = documentService.convertDocument(id, targetFormat, userId);
        return Result.success(newDocumentId);
    }

    @Operation(summary = "提取文档内容", description = "提取文档文本内容")
    @PostMapping("/{id}/extract")
    public Result<String> extractDocumentContent(@Parameter(description = "文档ID") @PathVariable String id) {
        String content = documentService.extractDocumentContent(id);
        return Result.success(content);
    }

    @Operation(summary = "生成文档摘要", description = "生成文档摘要")
    @PostMapping("/{id}/summary")
    public Result<String> generateDocumentSummary(@Parameter(description = "文档ID") @PathVariable String id) {
        String summary = documentService.generateDocumentSummary(id);
        return Result.success(summary);
    }

    @Operation(summary = "收藏文档", description = "收藏指定文档")
    @PostMapping("/{id}/favorite")
    public Result<Boolean> favoriteDocument(@Parameter(description = "文档ID") @PathVariable String id) {
        String userId = UserContext.getUserId();
        Boolean result = documentService.favoriteDocument(id, userId);
        return Result.success(result);
    }

    @Operation(summary = "取消收藏文档", description = "取消收藏指定文档")
    @DeleteMapping("/{id}/favorite")
    public Result<Boolean> unfavoriteDocument(@Parameter(description = "文档ID") @PathVariable String id) {
        String userId = UserContext.getUserId();
        Boolean result = documentService.unfavoriteDocument(id, userId);
        return Result.success(result);
    }

    @Operation(summary = "复制文档", description = "复制现有文档")
    @PostMapping("/{id}/copy")
    public Result<DocumentVO> copyDocument(
            @Parameter(description = "文档ID") @PathVariable String id,
            @Parameter(description = "新文档名称") @RequestParam String newName) {
        String userId = UserContext.getUserId();
        DocumentVO document = documentService.copyDocument(id, newName, userId);
        return Result.success(document);
    }

    @Operation(summary = "移动文档", description = "移动文档到指定分类")
    @PostMapping("/move")
    public Result<Boolean> moveDocuments(
            @Parameter(description = "文档ID列表") @RequestBody List<String> documentIds,
            @Parameter(description = "目标分类ID") @RequestParam String categoryId) {
        Boolean result = documentService.moveDocuments(documentIds, categoryId);
        return Result.success(result);
    }

    @Operation(summary = "获取文档版本", description = "获取文档版本列表")
    @GetMapping("/{id}/versions")
    public Result<List<DocumentVO>> getDocumentVersions(@Parameter(description = "文档ID") @PathVariable String id) {
        List<DocumentVO> versions = documentService.getDocumentVersions(id);
        return Result.success(versions);
    }

    @Operation(summary = "创建文档版本", description = "创建新的文档版本")
    @PostMapping("/{id}/versions")
    public Result<String> createDocumentVersion(
            @Parameter(description = "文档ID") @PathVariable String id,
            @Parameter(description = "版本描述") @RequestParam String description) {
        String userId = UserContext.getUserId();
        String versionId = documentService.createDocumentVersion(id, description, userId);
        return Result.success(versionId);
    }

    @Operation(summary = "恢复文档版本", description = "恢复到指定版本")
    @PostMapping("/{id}/versions/{versionId}/restore")
    public Result<Boolean> restoreDocumentVersion(
            @Parameter(description = "文档ID") @PathVariable String id,
            @Parameter(description = "版本ID") @PathVariable String versionId) {
        String userId = UserContext.getUserId();
        Boolean result = documentService.restoreDocumentVersion(id, versionId, userId);
        return Result.success(result);
    }

    @Operation(summary = "获取文档统计", description = "获取文档统计信息")
    @GetMapping("/{id}/statistics")
    public Result<DocumentStatisticsVO> getDocumentStatistics(@Parameter(description = "文档ID") @PathVariable String id) {
        DocumentStatisticsVO statistics = documentService.getDocumentStatistics(id);
        return Result.success(statistics);
    }

    @Operation(summary = "获取存储统计", description = "获取用户文档存储统计")
    @GetMapping("/storage/statistics")
    public Result<DocumentStatisticsVO> getDocumentStorageStatistics() {
        String userId = UserContext.getUserId();
        DocumentStatisticsVO statistics = documentService.getDocumentStorageStatistics(userId);
        return Result.success(statistics);
    }
}
